package controllers

import (
	beego "github.com/beego/beego/v2/server/web"
	"math"
	models2 "user/models"
)

type UserController struct {
	beego.Controller
}

type JsonR struct {
	Code int         `json:"code"`
	Msg  string      `json:"msg"`
	Data interface{} `json:"data"`
}

type JsonPage struct {
	Code    int         `json:"code"`
	Msg     string      `json:"msg"`
	Data    interface{} `json:"data"`
	Page    int         `json:"page"`
	Sumpage int         `json:"sumpage"`
	Size    int         `json:"size"`
	Count   int64       `json:"count"`
}

func (c *UserController) List() {
	page, _ := c.GetInt("page", 1)
	size, _ := c.GetInt("size", 5)
	var count int64
	models2.DB.Model(&models2.User{}).Count(&count)
	sumpage := int(math.Ceil(float64(count) / float64(size)))
	if page > sumpage {
		page = sumpage
	}
	offset := (page - 1) * size
	var all []models2.User
	name := c.GetString("name")
	where := map[string]string{}
	if name != "" {
		where["name"] = name
	}
	err := models2.DB.Offset(offset).Where(where).Limit(size).Find(&all).Error
	if err != nil {
		c.Data["json"] = JsonR{
			Code: 500,
			Msg:  "查询失败",
			Data: nil,
		}
		c.ServeJSON()
	} else {
		c.Data["json"] = JsonPage{
			Code:    200,
			Msg:     "查询分页成功",
			Data:    all,
			Page:    page,
			Sumpage: sumpage,
			Size:    size,
			Count:   count,
		}
		c.ServeJSON()
	}
}
